package com.shigen.demo.shorturl.controller;

import com.shigen.demo.shorturl.service.IShortLinkService;
import com.shigen.demo.shorturl.util.HttpUrlValidator;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView;

/**
 * @author shigenfu
 * @date 2023/10/14 12:49
 */
@Controller
@RequestMapping
public class ShortLinkController {

    public static final String REDIRECT = "redirect:";

    @Resource
    private IShortLinkService shortLinkService;

    @GetMapping(value = "/shortlink/{code}")
    public RedirectView getLink(@PathVariable String code) {
        String url = shortLinkService.getLink(code);
        return new RedirectView(url);
    }

    @GetMapping(value = "shortlink")
    public RedirectView saveLink(@RequestParam("url") String url) {
        // 验证url是否是正确的格式
        if (!HttpUrlValidator.isHttpUrl(url)) {
            // 扔出异常
            throw new IllegalArgumentException("url is not valid");
        }
        String code = shortLinkService.saveLink(url);
        return new RedirectView(url);
    }

}
